package auctions;

import java.awt.BorderLayout;
import java.awt.Dimension;

import java.util.Hashtable;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableModel;


public class UserInterface extends JFrame {
    private BorderLayout layoutMain = new BorderLayout();
    private JScrollPane messagePane = new JScrollPane();
    private JTextArea biddingTextArea = new JTextArea();
    private JScrollPane buyersPane = new JScrollPane();
    private JTable buyersTable;
    
    private Hashtable<String, Integer> namesMap;

    public UserInterface(int numOfBuyers, String[] names) {
        createBuyersTable(numOfBuyers, names);
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void addAuctionMessage(String message) {
        biddingTextArea.setText(biddingTextArea.getText() + "\n" + message);
    }

    private void jbInit() throws Exception {
        this.getContentPane().setLayout( layoutMain );
        this.setSize( new Dimension(400, 300) );
        this.setTitle( "Auctions Simulation" );
        biddingTextArea.setEditable(false);
        messagePane.getViewport().add(biddingTextArea, null);
        this.getContentPane().add(messagePane, BorderLayout.NORTH);
        buyersPane.getViewport().add(buyersTable, null);
        this.getContentPane().add(buyersPane, BorderLayout.CENTER);
    }
    
    private void createBuyersTable(int numOfBuyers, String[] buyerNames) {
        Object[] columnNames = {"Buyer name", "Items left to buy", "Budget"};
        DefaultTableModel tm = new DefaultTableModel(columnNames, numOfBuyers);
        buyersTable = new JTable(tm);
        namesMap = new Hashtable<String, Integer>();
        for (int i = 0; i < buyerNames.length; i++) {
            namesMap.put(buyerNames[i], i);
            tm.setValueAt(buyerNames[i], i, 0);
        }
    }
    
    void updateBuyerInfo(String buyerName, int budget, int items) {
        int id = namesMap.get(buyerName);
        DefaultTableModel tm = (DefaultTableModel)buyersTable.getModel();
        tm.setValueAt(items, id, 1);
        tm.setValueAt(budget, id, 2);
    }
}
